from odoo import api, fields, models
from odoo.exceptions import UserError
from .rp_marketing_adjust_price_template import VALUE_CATEGORY
from ...functions.marketing_coupon_func import MarketingCouponFunc
from ..primary.rp_customer_coupon import COUPON_TYPE

COUPON_STATE = [('draft', '草稿'), ('enable', '激活'), ('expired', '弃用')]
DISCOUNT_ELIGIBILITY = [('all_mail_route', '所有邮路'), ('single_value_add', '单一增值'), ('single_route', '单一邮路'), ('all_value_add', '所有增值(二类)')]
TIME_OPTION = [('according_rule', '默认'), ('custom', '自定义')]
VALIDITY_SELECTION = [('day', '天'), ('week', '周'), ('month', '月'), ('year', '年')]


class RpMarketingCouponTemplate(models.Model):
    _name = 'rp.marketing.coupon.template'
    _description = '优惠券模板'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _sql_constraints = [('code', 'UNIQUE(code)', '优惠券的编码需要一致')]

    # 基本信息
    name = fields.Char(string='名称', required=True, copy=False, index=True, tracking=True)
    code = fields.Char(string='编码', default='RP_CO/****', readonly=True, index=True, copy=False, tracking=True)
    active_tag = fields.Boolean(string='有效标志 ', compute='depends_on_state', copy=False, tracking=True)
    is_stacked = fields.Boolean(string='叠加', required=True, copy=False, tracking=True)
    coupon_type = fields.Selection(string='优惠券类型', selection=COUPON_TYPE, required=True, copy=False, tracking=True)
    acquire_count = fields.Integer(string='获取次数', default=0, copy=False, index=True, tracking=True)
    usage_number = fields.Integer(string='使用次数', default=0, copy=False, index=True, tracking=True)
    state = fields.Selection(string='状态', selection=COUPON_STATE, default=COUPON_STATE[0][0], required=True, copy=False, tracking=True)
    currency_id = fields.Many2one(string='货币单位', comodel_name='res.currency', default=lambda self: self.env.company.currency_id)

    # 时效信息
    start_date_option = fields.Selection(string='开始选项', selection=TIME_OPTION, default=TIME_OPTION[0][0], required=True, copy=False, tracking=True)
    start_date = fields.Date(string='开始时间', copy=False, tracking=True)
    end_date_option = fields.Selection(string='结束选项', selection=TIME_OPTION, default=TIME_OPTION[0][0], required=True, copy=False, tracking=True)
    end_date = fields.Date(string='结束时间', copy=False, tracking=True)
    rp_coupon_validity_selection = fields.Selection(string='生效选项', selection=VALIDITY_SELECTION, default=VALIDITY_SELECTION[0][0], copy=False, tracking=True)
    rp_coupon_validity = fields.Integer(string='时效', store=True, copy=False, tracking=True, index=True)
    remark = fields.Text(string='备注', copy=False)

    # 优惠规则信息
    coupon_threshold = fields.Float(string='门槛', required=True, copy=False, tracking=True)
    par_value = fields.Float(string='面值', required=True, copy=False, tracking=True)
    discount_value = fields.Float(string='折扣值', required=True, copy=False, tracking=True)
    coupon_for = fields.Selection(string='优惠对象', selection=DISCOUNT_ELIGIBILITY, default=DISCOUNT_ELIGIBILITY[0][0], required=True, copy=False, tracking=True)
    rp_coupon_mail_route_id = fields.Many2one(string='单一邮路', comodel_name='rp.shipper.mail.route', copy=False, tracking=True)
    value_added_selection = fields.Selection(string='增值服务', selection=VALUE_CATEGORY, default=VALUE_CATEGORY[0][0], copy=False)
    rp_coupon_valued_added_id = fields.Many2one(string='增值服务', comodel_name='rp.shipper.sale.template.value.added.line', copy=False, tracking=True)

    def turn_expired(self):
        """弃用模板"""
        self.write({'state': COUPON_STATE[2][0], 'active_tag': False})

    def turn_enable(self):
        self.ensure_one()
        if self.end_date and self.end_date < fields.Date.today():
            raise UserError('此优惠券模板已失效！')
        self.write({'state': COUPON_STATE[1][0]})

    @api.depends('state')
    def depends_on_state(self):
        for record in self:
            if record.state == 'draft':
                record.write({'active_tag': False})
            if record.state == 'enable':
                record.write({'active_tag': True})
            if record.state == 'expired':
                record.write({'active_tag': False})

    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            vals['state'] = COUPON_STATE[1][0]
            vals['code'] = self.env['ir.sequence'].sudo().next_by_code('rp.marketing.coupon.template') or '/'
        return super(RpMarketingCouponTemplate, self).create(vals_list)

    @api.onchange('coupon_for')
    def onchange_coupon_for(self):
        if self.coupon_for == 'single_route':
            self.update({'rp_coupon_valued_added_id': False})
        if self.coupon_for == 'all_mail_route':
            self.update({'rp_coupon_valued_added_id': False, 'rp_coupon_mail_route_id': False})
        if self.coupon_for == 'single_value_add':
            self.update({'rp_coupon_mail_route_id': False})
        if self.coupon_for == 'all_value_add':
            self.update({'rp_coupon_mail_route_id': False, 'rp_coupon_valued_added_id': False, 'value_added_selection': False})

    @api.onchange('coupon_type')
    def onchange_coupon_type(self):
        self.write({'discount_value': False, 'par_value': False, 'coupon_threshold': False})

    @api.onchange('value_added_selection')
    def onchange_value_added_selection(self):
        self.update({'rp_coupon_valued_added_id': False})

    @api.onchange('start_date_option', 'end_date_option', 'rp_coupon_validity_selection', 'rp_coupon_validity')
    def onchange_for_date_options(self):
        if self.start_date_option == 'according_rule':
            self.update({'start_date': False})
        if self.end_date_option == 'according_rule':
            if self.start_date_option == 'custom' and self.start_date:
                end_date = MarketingCouponFunc(self.env).calculate_time(self.rp_coupon_validity_selection, self.start_date, self.rp_coupon_validity)
                self.with_context(no_onchange=True).update({'end_date': end_date})
            else:
                self.with_context(no_onchange=True).update({'end_date': False})
        # 当前仅当开始选项为默认，结束选项为自定义，时效失效
        if self.start_date_option == 'according_rule' and self.end_date_option == 'custom':
            self.update({'rp_coupon_validity_selection': False, 'rp_coupon_validity': False})

    @api.constrains('start_date', 'end_date')
    def _constrains_start_end_date(self):
        if self.start_date and self.end_date:
            if self.start_date >= self.end_date:
                raise UserError('结束时间应该在开始时间之后！')
            if self.end_date <= fields.Date.today():
                raise UserError('不可以创建无效的优惠券！')
            if self.coupon_type == COUPON_TYPE[1][0]:
                if self.discount_value <= 0.0 or self.discount_value > 1:
                    raise UserError('请输入有效的折扣值！')

    @api.constrains('coupon_type', 'discount_value')
    def _constrains_coupon_type_and_value(self):
        if self.coupon_type == COUPON_TYPE[1][0]:
            if self.discount_value <= 0.0 or self.discount_value > 1:
                raise UserError('请输入有效的折扣值！')

    @api.onchange('start_date', 'end_date')
    def calculate_validate_time(self):
        if self.env.context.get('onchange', False):
            if self.start_date and self.end_date:
                self.update({'rp_coupon_validity_selection': VALIDITY_SELECTION[0][0], 'rp_coupon_validity': (self.end_date - self.start_date).days})
